﻿Imports System.IO
Imports System.Text
Imports Microsoft
Imports System.Data.SqlClient
Imports System.Data.Sql
Imports DataObject
Imports Microsoft.ApplicationBlocks.Data
Imports Microsoft.SqlServer.Management.Smo
Public Class FrmLogin

    Dim sNameServer As String = ""
    Dim sUserName As String = ""
    Dim sPassword As String = ""
    Dim oTable As New Data.DataTable
    Dim oConnect As New SqlConnection
    Dim oSqlCmd As New SqlCommand
    Dim oSqlDa As New SqlDataAdapter

#Region "Function & Sub"

    Private Sub MesError(ByVal Error_ As Integer)
        If (Error_ = 1) Then
            MessageBox.Show("Chưa điền tên đăng nhập", "Thông báo lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
        ElseIf (Error_ = 2) Then
            MessageBox.Show("Chưa điền mật khẩu đăng nhập", "Thông báo lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
        ElseIf (Error_ = 3) Then
            MessageBox.Show("Chưa điền tên và mật khẩu đăng nhập", "Thông báo lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
        ElseIf (Error_ = 4) Then
            MessageBox.Show("Tên đăng nhập không đúng", "Thông báo lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
        ElseIf (Error_ = 5) Then
            MessageBox.Show("Mật khẩu đăng nhập không đúng", "Thông báo lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
        ElseIf (Error_ = 6) Then
            MessageBox.Show("Tên và mật khẩu đăng nhập không đúng", "Thông báo lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error)
            'Lỗi file CSDL 
        ElseIf (Error_ = 7) Then
            MessageBox.Show("Định dạng tệp tin CSDL không chính xác", "Thông báo lỗi", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

    Private Sub CreatFileLog(ByVal flags As Integer)
        If Not System.IO.Directory.Exists(Application.StartupPath & "\FileLogs\") Then
            System.IO.Directory.CreateDirectory(Application.StartupPath & "\FileLogs\")
        End If
        'Kiểm tra sự tồn tại của file logs
        Dim objFileLogs As FileStream = New FileStream(Application.StartupPath & "\FileLogs\logs.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
        Dim objWriteFileLogs As StreamWriter = New StreamWriter(objFileLogs)
        objWriteFileLogs.Close()
        objFileLogs.Close()

        Dim objFileLogs_ As FileStream = New FileStream(Application.StartupPath & "\FileLogs\logs.txt", FileMode.Append, FileAccess.Write)
        Dim objWriteFileLogs_ As StreamWriter = New StreamWriter(objFileLogs_)
        'Viết thông tin vào file logs
        If (flags = 1) Then
            objWriteFileLogs_.Write("Ten dang nhap: " & sUserName & vbCrLf)
            objWriteFileLogs_.Write("Mat khau dang nhap: " & sPassword & vbCrLf)
            objWriteFileLogs_.Write("Ngay/Thoi gian dang nhap: " & DateTime.Now.ToString() & vbCrLf)
            objWriteFileLogs_.Write("Dang nhap thanh cong" & vbCrLf)
            objWriteFileLogs_.Write("================================================" & vbCrLf)
            objWriteFileLogs_.Close()
        Else
            'Không làm gì cả
        End If
        'Giải phóng
        objFileLogs_.Close()
    End Sub

    Private Sub GetServerList()
        'Load dữ liệu cho combobox cboServer : Tìm các server tồn tại trong máy
        With cboServer
            .Items.Clear()
        End With
        oTable = SmoApplication.EnumAvailableSqlServers(False)
        For Each oRow As Data.DataRow In oTable.Rows
            sNameServer = oRow("Server").ToString
            If (Not Convert.IsDBNull(oRow("Instance")) And oRow("Instance").ToString().Length > 0) Then
                sNameServer += "\" & oRow("Instance").ToString()
            ElseIf cboServer.Items.IndexOf(sNameServer) < 0 Then
                cboServer.Items.Add(sNameServer)
            ElseIf cboServer.Items.Count > 0 Then
                cboServer.SelectedIndex = 0
            End If
        Next
    End Sub

    Private Sub GetDatabaseList()
        Try
            With cboDatabase
                .Items.Clear()
            End With
            cboDatabase.Items.Clear()
            Dim oDataReader As SqlClient.SqlDataReader

            Dim conn As New SqlClient.SqlConnection
            Dim cmd As New SqlClient.SqlCommand
            'Persist Security Info=True
            If cboAuthentication.Text = cboAuthentication.Items.Item(0).ToString Then
                conn = New SqlClient.SqlConnection("Data source = " & cboServer.Text & "; Initial Catalog = Master; Integrated Security = True")
                'conn = New SqlClient.SqlConnection("Data source = " & cboServer.Text & "; Initial Catalog = Master; Persist Security Info=True")
            ElseIf cboAuthentication.Text = cboAuthentication.Items.Item(1).ToString Then
                'conn = New SqlClient.SqlConnection("Data source = " & cboServer.Text & "; Initial Catalog = Master; Integrated Security = True; User = " & txtUsername.Text & "; Password = " & txtPassword.Text & ";")
                conn = New SqlClient.SqlConnection("Data source = " & cboServer.Text & "; Initial Catalog = Master; Persist Security Info=True; User = " & txtUsername.Text & "; Password = " & txtPassword.Text & ";")
            End If
            conn.Open()
            cmd = New SqlClient.SqlCommand("SELECT * FROM sys.Databases", conn)
            oDataReader = cmd.ExecuteReader()
            While oDataReader.Read()
                cboDatabase.Items.Add(oDataReader(0))
            End While
        Catch ex As Exception
        End Try
    End Sub

    Private Sub CheckLoginBy()
        If cboAuthentication.Text = cboAuthentication.Items.Item(0).ToString Then
            LoadDesign(0)
            lbDatabase.Enabled = True
            cboDatabase.Enabled = True
            sUserName = My.User.Name
            txtUsername.Text = sUserName
            GetDatabaseList()
        ElseIf cboAuthentication.Text = cboAuthentication.Items.Item(1).ToString Then
            LoadDesign(1)
            If txtUsername.Text <> "" And txtPassword.Text <> "" Then
                GetDatabaseList()
            End If
        End If
    End Sub

    Private Sub LoadDesign(ByVal iflag As Integer)
        If (iflag = 0) Then
            txtPassword.Text = ""
            txtUsername.Text = ""
            cboDatabase.Text = ""
            lblUserName.Enabled = False
            lblPassword.Enabled = False
            txtPassword.Enabled = False
            txtUsername.Enabled = False
            lbDatabase.Enabled = False
            cboDatabase.Enabled = False
        Else
            txtPassword.Text = ""
            txtUsername.Text = "sa"
            lblUserName.Enabled = True
            lblPassword.Enabled = True
            txtPassword.Enabled = True
            txtUsername.Enabled = True
            lbDatabase.Enabled = True
            cboDatabase.Enabled = True
        End If
    End Sub

    Private Sub LoadSettingsFrom(ByVal sFileName As String)
        Dim oDataset As New DataSet
        If Not My.Computer.FileSystem.FileExists(sFileName) Then
            Exit Sub
        End If
        If (My.Computer.FileSystem.FileExists(sFileName)) Then
            oDataset.ReadXml(sFileName)
            Dim oDatatable As DataTable
            oDatatable = oDataset.Tables("FileConfig")
            oDatatable = oDataset.Tables(0)
            If oDatatable.Rows.Count > 0 Then
                cboServer.Text = oDatatable.Rows(0)("Server")
                cboAuthentication.Text = oDatatable.Rows(0)("Authentication")
                txtUsername.Text = oDatatable.Rows(0)("UserName")
                txtPassword.Text = oDatatable.Rows(0)("Password")
                cboDatabase.Text = oDatatable.Rows(0)("Database")
            Else
                cboServer.Text = ""
                cboAuthentication.Text = ""
                txtUsername.Text = ""
                txtPassword.Text = ""
                cboDatabase.Text = ""
            End If
        End If
    End Sub

    Private Sub SaveSettingsAs(ByVal sFileName As String)

        Dim oTable As New DataTable
        Dim oDataset As New DataSet

        'Lưu setting database, server etc
        oTable.Columns.Add("Server", "".GetType)
        oTable.Columns.Add("Authentication", "".GetType)
        oTable.Columns.Add("UserName", "".GetType)
        oTable.Columns.Add("Password", "".GetType)
        oTable.Columns.Add("Database", "".GetType)
        oTable.Rows.Add(New Object() {cboServer.Text, cboAuthentication.Text, txtUsername.Text, txtPassword.Text, cboDatabase.Text})

        oTable.TableName = "DefaultValues"
        oDataset.Tables.Add(oTable)

        Dim oDTPresetNew As New DataTable
        oDTPresetNew.TableName = "Preset"
        oDTPresetNew.Columns.Add("Server", "".GetType())
        oDTPresetNew.Columns.Add("Authentication", "".GetType())
        oDTPresetNew.Columns.Add("UserName", "".GetType())
        oDTPresetNew.Columns.Add("Password", "".GetType())
        oDTPresetNew.Columns.Add("Database", "".GetType())

        Dim DTPreset As DataTable
        Dim DSPreset As New DataSet

        'Kiểm tra sự tồn tại của file
        If (My.Computer.FileSystem.FileExists(sFileName)) Then
            DSPreset.ReadXml(sFileName)
            DTPreset = DSPreset.Tables("FileConfig")
        End If

        If (Not IsNothing(DTPreset)) Then
            oDTPresetNew = DTPreset.Copy()
        End If

        Dim i As Integer
        Dim bFound As Boolean = False
        For i = 0 To oDTPresetNew.Rows.Count - 1
            If oDTPresetNew.Rows(i)("Server").ToString().ToUpper() = cboServer.Text.ToUpper() Then
                bFound = True
                oDTPresetNew.Rows(i)("Authentication") = cboAuthentication.Text
                oDTPresetNew.Rows(i)("UserName") = txtUsername.Text
                oDTPresetNew.Rows(i)("Password") = txtPassword.Text
            End If
        Next

        If (Not bFound) Then
            If (cboServer.Text.Trim() <> "") Then
                oDTPresetNew.Rows.Add(New Object() {cboServer.Text, cboAuthentication.Text, txtUsername.Text, txtPassword.Text, cboDatabase.Text})
            End If
        End If
        oDataset.Tables.Add(oDTPresetNew)
        oDataset.WriteXml(sFileName)
        oDataset.Tables.Clear()
    End Sub

    Private Sub LoadStatus()
        FrmMain.tbrFooter.Panels("mnuFooter_Username").Text = "Tên đăng nhập : " & txtUsername.Text
        FrmMain.tbrFooter.Panels("mnuFooter_Database").Text = "CSDL : " & cboDatabase.Text
    End Sub

#End Region

    Private Sub FrmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LoadDesign(0)
        'GetServerList()
        LoadSettingsFrom(My.Application.Info.DirectoryPath + "\DefaultValues.ConfigSettings")
        Me.btnLogin.Focus()
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub

    Private Sub cboAuthentication_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboAuthentication.ValueChanged
        CheckLoginBy()
    End Sub

    Private Sub txtPassword_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPassword.ValueChanged
        Try
            If (txtPassword.Text <> "") Then
                GetDatabaseList()
            End If
        Catch ex As Exception
        End Try
    End Sub

    Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
        Dim oConn As New hDBase
        Try
            If cboAuthentication.Text = cboAuthentication.Items.Item(0).ToString Then
                sConn = "Data source = " & cboServer.Text & "; Initial Catalog = " & cboDatabase.Text & "; Integrated Security = True"
                'sConn = "Data source = " & cboServer.Text & "; Initial Catalog = " & cboDatabase.Text & "; Persist Security Info = True"
            ElseIf cboAuthentication.Text = cboAuthentication.Items.Item(1).ToString Then
                'sConn = "Data source = " & cboServer.Text & "; Initial Catalog = " & cboDatabase.Text & "; Integrated Security = True; User = " & txtUsername.Text & "; Password = " & txtPassword.Text & ";"
                sConn = "Data source = " & cboServer.Text & "; Initial Catalog = " & cboDatabase.Text & "; Persist Security Info = True; User = " & txtUsername.Text & "; Password = " & txtPassword.Text & ";"
            End If
            oConn.Connection(sConn)
            FrmMain.Show()
            FrmMain.Enabled = True
            SaveSettingsAs(My.Application.Info.DirectoryPath + "\DefaultValues.ConfigSettings")
            LoadStatus()
            Me.Close()
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

End Class
